const { default: request } = require("../../plugins/request")
const { default: store } = require("../../utils/store")
const {
	valIsNull,
	handleUrlParams,
	valIsEmpty,
	controlShowPage,
} = require("../../utils/utils")

const pageOptions = {
	// 页面数据
	data: {
		isFirstOnShow: true, // 是否为首次执行onShow
		faceBase64Row: "", // 人脸照片
		faceBase64: "", // 人脸照片
		faceImageId: "", // 人脸照片id用于提交s
		permissionToAccessCamera: true, // 是否允许访问摄像头
		showCamera: true, // 调用onHide钩子隐藏页面时把相机销毁，onShow钩子显示页面时重新创建相机，解决用户更改授权时相机不显示的问题
		replaceBg: false, // 是否替换背景
		shot: false, // 是否已拍照
		showPage: false, // 是否显示页面，用于微信审核
	},
	// 页面载入时
	onLoad(e) {
		this.init(e)
	},
	// 页面初始化
	init(e) {
		this.setData({
			replaceBg: store.replaceBg.get(),
		})
	},
	// 页面准备好时
	onReady() {},
	// 页面显示时
	async onShow() {
		this.setData({
			showPage: await controlShowPage(),
		})
		if (store.face.get()) {
			this.setData({
				showCamera: true,
				faceBase64Row: store.face.get(),
				faceBase64: "data:image/jpeg;base64," + store.face.get(),
			})
		} else {
			this.setData({
				showCamera: true,
			})
		}
	},
	// 页面隐藏时
	onHide() {
		this.setData({
			showCamera: false,
		})
	},
	// 页面卸载时
	onUnload() {},
	// 下拉页面时
	onPullDownRefresh() {},
	// 到达页面底部时
	onReachBottom() {},
	// 页面滚动时
	onPageScroll() {},
	// 分享时，注：onShareAppMessage不能为async异步函数，会导致不能及时取得返回值，使得分享设置无效
	onShareAppMessage() {
		/* const title = ''
    const path = ''
    const imageUrl = ``

    return {
      title,
      path,
      imageUrl,
    } */
	},
	//用户拒绝访问相机
	refuseToAccessCamera() {
		this.setData({
			permissionToAccessCamera: false,
		})
	},
	//相机初始化完成时触发
	handleCameraInitDone() {
		this.setData({
			permissionToAccessCamera: true,
		})
	},
	//拍照
	takePhoto() {
		if (this.data.permissionToAccessCamera === false) {
			wx.showToast({
				title: "无访问相机权限，请先授权",
				icon: "none",
			})
			return
		}
		const ctx = wx.createCameraContext()
		ctx.takePhoto({
			quality: "high",
			success: (res) => {
				//转成base64
				wx.getFileSystemManager().readFile({
					filePath: res.tempImagePath,
					encoding: "base64",
					success: (res) => {
						const base64String = res.data

						//将人脸照片进行背景模糊处理
						if (this.data.replaceBg) {
							//暂时停住相机
							this.setData({
								faceBase64: "data:image/jpeg;base64," + base64String,
							})
							wx.showLoading({
								title: "处理中",
							})
							request({
								url: "api/wx/xshy/replace-bg",
								method: "POST",
								data: {
									face: base64String,
								},
							})
								.then((res) => {
									wx.hideLoading()
									store.face.set(res.faceBase64Row)
									store.faceImageId.set(res.faceImageId)
									this.setData({
										faceBase64Row: res.faceImage,
										faceBase64: "data:image/jpeg;base64," + res.faceImage,
										faceImageId: res.faceImageId,
										shot: true,
									})
								})
								.catch((err) => {
									wx.hideLoading()
									console.log(err, "err")
									wx.showModal({
										title: "提示",
										content: err,
										showCancel: false,
										success: (res) => {
											// 重新拍照
											this.retake()
										},
									})
								})
							// 不需要模糊背景
						} else {
							store.face.set(base64String)
							this.setData({
								faceBase64Row: base64String,
								faceBase64: "data:image/jpeg;base64," + base64String,
								shot: true,
							})
						}
					},
				})
			},
			fail: (err) => {
				console.log(err, "err")
			},
		})
	},
	//重拍
	retake() {
		this.setData({
			faceBase64Row: "",
			faceBase64: "",
			faceImageId: "",
			shot: false,
		})
		store.face.set("")
	},
	//提交核验
	submit() {
		//从缓存中取出要提交的数据
		const params = {
			face: store.face.get() ? store.face.get() : "",
			faceImageId: store.faceImageId.get()
				? store.faceImageId.get()
				: undefined,
			location: store.location.get() ? store.location.get() : undefined,
			sfz_front: store.sfz_front.get() ? store.sfz_front.get() : undefined,
			sfz_back: store.sfz_back.get() ? store.sfz_back.get() : undefined,
		}
		//检查是否有上传位置
		// if (valIsEmpty(params.location)) {
		// 	wx.showToast({
		// 		title: "请先获取位置信息",
		// 		icon: "none",
		// 	})
		// 	return
		// }
		wx.showLoading({
			title: "提交中",
		})
		request({
			url: "api/wx/xshy/verify",
			method: "POST",
			data: params,
			row: true,
		})
			.then((res) => {
				const data = res.data.data
				const msg = res.data.msg
				wx.hideLoading()
				//记录待核验的次数
				store.maxRetryCount.set(data.reCount)
				//跳转到核验审核中页面
				let url
				//核验通过
				if (data.zzjg === 1) {
					url = handleUrlParams(
						"/informationVerification/pages/verificationResult/index",
						{
							auditStatus: "pass",
							recordId: data.recordId,
							checkDate: data.yzsj,
						},
					)
					//核验不通过
				} else if (data.zzjg === 0) {
					url = handleUrlParams(
						"/informationVerification/pages/verificationResult/index",
						{
							auditStatus: "reject",
							recordId: data.recordId,
							checkDate: data.yzsj,
							rejectReason: msg,
						},
					)
					//存疑
				}
				// else if (data.zzjg === 2) {
				// 	url = handleUrlParams(
				// 		"/informationVerification/pages/verificationResult/index",
				// 		{
				// 			auditStatus: "doubtWaitAudit",
				// 			recordId: data.recordId,
				// 			checkDate: data.yzsj,
				// 			rejectReason: msg,
				// 		},
				// 	)
				// }
				else {
					let rejectReason = ""
					if (data.detail) {
						const detail = JSON.parse(data.detail)
						rejectReason = msg + "；"
						for (const item of detail) {
							rejectReason += item.remark + "；"
						}
						// rejectReason = msg + "；" + detail[0].remark
					}
					url = handleUrlParams(
						"/informationVerification/pages/verificationResult/index",
						{
							auditStatus: data.zzjg,
							maxRetryCount: data.reCount,
							recordId: data.recordId,
							checkDate: data.yzsj,
							rejectReason: rejectReason ? rejectReason : msg,
						},
					)
				}
				wx.redirectTo({
					url,
				})
			})
			.catch((err) => {
				// const data = res.data.data
				console.log(err, "err")
				//核验失败
				let url = handleUrlParams(
					"/informationVerification/pages/verificationResult/index",
					{
						auditStatus: "reject",
						rejectReason: err,
					},
				)
				wx.redirectTo({
					url,
				})
				return
			})
	},
}

Page(pageOptions)
